package com.hfjyz.system.user.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hfjyz.base.bean.SearchCondition;
import com.hfjyz.base.constant.BaseConstant;
import com.hfjyz.base.entity.DepartEntity;
import com.hfjyz.base.entity.UserEntity;
import com.hfjyz.base.exception.BaseException;
import com.hfjyz.base.util.BaseUtil;
import com.hfjyz.base.util.MD5;
import com.hfjyz.system.depart.bean.DepartBean;
import com.hfjyz.system.depart.dao.DepartDao;
import com.hfjyz.system.user.bean.UserBean;
import com.hfjyz.system.user.dao.UserDao;

public class UserService {
    private static final Log SYS_LOG = LogFactory.getLog(BaseConstant.SYS_LOG);
    private UserDao dao = null;
    
    private DepartDao departDao = null;

    public UserDao getDao() {
        return dao;
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }

    public DepartDao getDepartDao() {
        return departDao;
    }

    public void setDepartDao(DepartDao departDao) {
        this.departDao = departDao;
    }

    public List<UserBean> findUser(SearchCondition searchCondition) throws BaseException {
        try {
            List<UserEntity> userList = dao.findUser(searchCondition);

            List<UserBean> beanList = new ArrayList<UserBean>();
            for (UserEntity entity : userList) {
                UserBean bean = new UserBean(entity);
                beanList.add(bean);
            }

            SYS_LOG.info("用户检索成功。");
            return beanList;
        } catch (Exception e) {
            SYS_LOG.error("用户检索失败！", e);
            throw new BaseException("用户检索失败！", e);
        }
    }

    public long getUserCount(SearchCondition searchCondition) throws BaseException {
        try {
            long count = dao.countUser(searchCondition);
            SYS_LOG.info("用户总数获取成功！总数=" + count);
            
            return count;
        } catch (Exception e) {
            SYS_LOG.error("用户总数获取失败！", e);
            throw new BaseException("用户总数获取失败！", e);
        }
    }

    public void saveUser(UserBean bean) throws BaseException {
        try {
            String msg = bean.validate();
            if (msg != null && !msg.isEmpty()) {
                throw new BaseException(msg);
            }
            UserEntity entity = new UserEntity();
            entity.setId(bean.getId());
            entity.setUserId(bean.getUserId());
            entity.setUserName(bean.getUserName());
            entity.setPassword(bean.getPassword());
            entity.setIsMale(bean.getSex() == 1);
            DepartEntity depart = new DepartEntity();
            depart.setId(bean.getDepartId());
            entity.setDepart(depart);

            if (bean.getBirthday() != null && bean.getBirthday().length() > 0) {
                Date birthday = BaseUtil.parseDate(bean.getBirthday());
                entity.setBirthday(birthday);
            }

            dao.saveOrUpdate(entity);

            SYS_LOG.info("用户信息保存成功。 user=" + bean.toString());
        } catch (BaseException e) {
            SYS_LOG.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            SYS_LOG.error("用户信息保存过程中发生错误！", e);
            throw new BaseException("用户信息保存过程中发生错误！", e);
        }
        
    }

    public void deleteUser(List<Integer> idList) throws BaseException {
        try {
            for (Integer id : idList) {
                dao.delete(id);
            }
            SYS_LOG.info("用户删除成功。 idList=" + idList.toString());
        } catch (Exception e) {
            SYS_LOG.error("用户删除失败。", e);
            throw new BaseException("用户删除失败。", e);
        }
    }

    public UserBean updateInitUser(Integer id) throws BaseException {
        try {
            UserEntity entity = dao.get(id);
            UserBean bean = new UserBean(entity);
            SYS_LOG.info("获取用户信息成功。 bean=" + bean);

            return bean;
        } catch (Exception e) {
            SYS_LOG.error("获取用户信息失败。", e);
            throw new BaseException("获取用户信息失败。", e);
        }
    }

    public void passwordChange(Integer id, String oldPassword, String newPassword) throws BaseException {
        try {
            UserEntity entity = dao.get(id);
            String encryptOldPassword = MD5.GetMD5Code(oldPassword);
            String encryptNewPassword = MD5.GetMD5Code(newPassword);
            if (encryptOldPassword.equals(entity.getPassword())) {
                entity.setPassword(encryptNewPassword);
                dao.saveOrUpdate(entity);
            } else {
                SYS_LOG.error("原密码不正确！");
                throw new BaseException("原密码不正确！");
            }
        } catch (Exception e) {
            SYS_LOG.error("密码修改过程中发生错误！", e);
            throw new BaseException("密码修改过程中发生错误！", e);
        }
    }

    public UserBean findUser(String userId) throws BaseException {
        UserEntity userEntity = null;
        try {
            userEntity = dao.findUserById(userId);
        } catch (Exception e) {
            SYS_LOG.error("获取用户信息失败！", e);
            throw new BaseException("获取用户信息失败！", e);
        }

        if (userEntity == null) {
            SYS_LOG.error("指定用户ID不存在！");
            throw new BaseException("指定用户ID不存在！");
        }
        return new UserBean(userEntity);
    }

    public void resetPassword(String userId, String newPassword) throws BaseException {
        UserEntity userEntity = null;
        try {
            userEntity = dao.findUserById(userId);
        } catch (Exception e) {
            SYS_LOG.error("获取用户信息失败！", e);
            throw new BaseException("获取用户信息失败！", e);
        }

        if (userEntity == null) {
            throw new BaseException("指定用户ID不存在！");
        }
        userEntity.setPassword(newPassword);
        
        try {
            dao.saveOrUpdate(userEntity);
        } catch (Exception e) {
            SYS_LOG.error("密码重置失败！", e);
            throw new BaseException("密码重置失败！", e);
        }
    }

    public List<DepartBean> listDepart() throws BaseException {
        try {
            List<DepartEntity> entityList = departDao.listDepart();
            List<DepartBean> deptList = new ArrayList<DepartBean>();
            for (DepartEntity entity : entityList) {
                deptList.add(new DepartBean(entity));
            }
            return deptList;
        } catch (Exception e) {
            SYS_LOG.error("获取部门信息失败！", e);
            throw new BaseException("获取部门信息失败！", e);
        }
    }
}
